/*
Copyright 2008  Four Roads LLC conact@4-roads.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using CommunityServer.Components;
using System.ComponentModel;
using System.Text;
using ResourceManager = FourRoads.Links.Controls.ResourceManager;

namespace FourRoads.Links.Controls
{
	public class SectionTrackedLinkButton : HtmlAnchor
	{

		#region Public Properties

		private bool _isTracked;
		private int _sectionid;

		public bool IsTracked
		{
			get{return _isTracked;}
			set{_isTracked = value;}
		}

		public int SectionID
		{
			get{return _sectionid;}
			set{_sectionid = value;}
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets whether images will be used with the button." ),
		DefaultValue( false ),
		]
		public virtual bool UseImages
		{
			get
			{
				Object state = ViewState["UseImages"];
				if(state != null)
					return (bool)state;
				return false;
			}
			set { ViewState["UseImages"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when tracking." ),
		DefaultValue( "" ),
		]
		public virtual string TrackingResourceName 
		{
			get 
			{
				Object state = ViewState["TrackingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["TrackingResourceName"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when not tracking." ),
		DefaultValue( "" ),
		]
		public virtual string NotTrackingResourceName 
		{
			get 
			{
				Object state = ViewState["NotTrackingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["NotTrackingResourceName"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when the button is working." ),
		DefaultValue( "" ),
		]
		public virtual string WorkingResourceName 
		{
			get 
			{
				Object state = ViewState["WorkingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["WorkingResourceName"] = value; }
		}

		[
		System.ComponentModel.DefaultValue("CommonImageTextButton")
		]
		public virtual String CssClass
		{
			get
			{
				Object state = ViewState["CssClass"];
				if ( state != null ) 
				{
					return (String)state;
				}
				return "CommonImageTextButton";
			}
			set
			{
				ViewState["CssClass"] = value;
			}
		}

		#endregion

		protected override void OnLoad(EventArgs e)
		{
			AjaxManager.Register(this,this.GetType().Name,true,AjaxDebug.None);
			base.OnLoad (e);
		}


		#region Control Wiring

		protected override void CreateChildControls()
		{
			if(CSContext.Current.User.IsAnonymous)
				return;

			if(UseImages)
			{
				this.Attributes.Add("onMouseOver", "javascript:subscriptionButtonOver();");
				this.Attributes.Add("onMouseOut", "javascript:subscriptionButtonOut();");
				this.Attributes.Add("onMouseDown", "this.style.backgroundImage = 'url(" + Globals.GetSkinPath() + "/images/common/tracktopic-wait.gif)';");
				this.Attributes.Add("class", this.CssClass);

				if(this.IsTracked)
				{
					this.Attributes.Add("style", "background-image: url(" + Globals.GetSkinPath() + "/images/common/tracktopic-on.gif);");
					this.InnerText = ResourceManager.GetString(TrackingResourceName);
				}
				else
				{
					this.Attributes.Add("style", "background-image: url(" + Globals.GetSkinPath() + "/images/common/tracktopic.gif);");
					this.InnerText = ResourceManager.GetString(NotTrackingResourceName);
				}
			}
			else
			{
				if(this.IsTracked)
					this.InnerText = ResourceManager.GetString(TrackingResourceName);
				else
					this.InnerText = ResourceManager.GetString(NotTrackingResourceName);
			}

			this.HRef = "javascript:toggleSubscription();";
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if(CSContext.Current.User.IsAnonymous)
				return;
			
			if(UseImages)
				BuildCallbackScriptWithImages();
			else
				BuildCallbackScript();
		}

		private void BuildCallbackScript()
		{
			StringBuilder sb = new StringBuilder();
			string uniqueID = this.ClientID;

			sb.Append("<script language='JavaScript' type=\"text/javascript\">");
			sb.AppendFormat("var {0}_trackWorking = false;", uniqueID);
			sb.AppendFormat("var {0}_trackStatus = {1};", uniqueID, this.IsTracked.ToString().ToLower());

			sb.Append("function updateSubscriptionText() {");
			sb.Append(  "if(" + uniqueID + "_trackStatus == true) {");
			if(TrackingResourceName != string.Empty)
				sb.Append(    "document.getElementById('" + uniqueID + "').innerHTML = '" + ResourceManager.GetString(TrackingResourceName).Replace("'", "\'") + "';");
			sb.Append(  "} else {");
			if(NotTrackingResourceName != string.Empty)
				sb.Append(    "document.getElementById('" + uniqueID + "').innerHTML = '" + ResourceManager.GetString(NotTrackingResourceName).Replace("'", "\'") + "';");
			sb.Append(  "}");
			sb.Append("}");

			sb.Append("function toggleSubscription() {");
			sb.Append(  uniqueID + "_trackWorking = true;");
			if(WorkingResourceName != string.Empty)
				sb.Append(  "document.getElementById('" + uniqueID + "').innerHTML = '" + ResourceManager.GetString(WorkingResourceName).Replace("'", "\'") + "';");
			sb.Append(  this.GetType().Name + ".ToggleEmailReplies('" + this.ClientID + "'," + this.SectionID +  ", toggleSubscriptionCallback);");
			sb.Append("}");

			sb.Append("function toggleSubscriptionCallback(response) {");
			sb.Append(  uniqueID + "_trackWorking = false;");

			sb.Append(  "if((response.error == null) && (response.value == true)) {");
			sb.Append(    "if(" + uniqueID + "_trackStatus == true) {");
			sb.Append(      uniqueID + "_trackStatus = false;");
			sb.Append(    "} else {");
			sb.Append(      uniqueID + "_trackStatus = true;");
			sb.Append(    "}");
			sb.Append(    "updateSubscriptionText();");
			sb.Append(  "} else {");
			sb.Append(    "updateSubscriptionText();");
			sb.Append(    "alert('" + ResourceManager.GetString("CallbackErrorResponse").Replace("'", "\'") + "');");
			sb.Append(  "}");
			sb.Append("}");
			sb.Append("</script>");

			Page.RegisterClientScriptBlock("ThreadSubscribeCallback", sb.ToString());
		}

		private void BuildCallbackScriptWithImages()
		{
			StringBuilder sb = new StringBuilder();
			string uniqueID = this.ClientID;
			string imageUniqueID = this.ClientID;

			sb.Append("<script language='JavaScript' type=\"text/javascript\">");
			sb.AppendFormat("var {0}_trackWorking = false;", uniqueID);
			sb.AppendFormat("var {0}_trackStatus = {1};", uniqueID, this.IsTracked.ToString().ToLower());

			sb.Append("function subscriptionButtonOut() {");
			sb.Append(  "if(" + uniqueID + "_trackWorking == false) {");
			sb.Append(    "if(" + uniqueID + "_trackStatus == true) {");
			sb.Append(		"document.getElementById('" + imageUniqueID + "').style.backgroundImage = 'url(" + Globals.GetSkinPath() + "/images/common/tracktopic-on.gif)';");
			if(TrackingResourceName != string.Empty)
			{
				sb.Append(      "document.getElementById('" + imageUniqueID + "').innerHTML = '" + ResourceManager.GetString(TrackingResourceName).Replace("'", "\'") + "';");
			}
			sb.Append(    "} else {");
			sb.Append(		"document.getElementById('" + imageUniqueID + "').style.backgroundImage = 'url(" + Globals.GetSkinPath() + "/images/common/tracktopic.gif)';");
			if(NotTrackingResourceName != string.Empty)
			{
				sb.Append(      "document.getElementById('" + imageUniqueID + "').innerHTML = '" + ResourceManager.GetString(NotTrackingResourceName).Replace("'", "\'") + "';");
			}
			sb.Append(    "}");
			sb.Append(  "}");
			sb.Append("}");

			sb.Append("function subscriptionButtonOver() {");
			sb.Append(  "if(" + uniqueID + "_trackWorking == false) {");
			if(WorkingResourceName != string.Empty)
			{
				sb.Append(    "document.getElementById('" + imageUniqueID + "').innerHTML = '" + ResourceManager.GetString(WorkingResourceName).Replace("'", "\'") + "';");
			}
			sb.Append(  "}");
			sb.Append("}");

			sb.Append("function toggleSubscription() {");
			sb.Append(  uniqueID + "_trackWorking = true;");
			sb.Append(  this.GetType().Name + ".ToggleEmailReplies('" + this.ClientID + "'," + this.SectionID + ", toggleSubscriptionCallback);");
			sb.Append("}");

			sb.Append("function toggleSubscriptionCallback(response) {");
			sb.Append(  uniqueID + "_trackWorking = false;");
			sb.Append(  "if((response.error == null) && (response.value == true)) {");
			sb.Append(    "if(" + uniqueID + "_trackStatus == true) {");
			sb.Append(      uniqueID + "_trackStatus = false;");
			sb.Append(      "subscriptionButtonOut();");
			sb.Append(    "} else {");
			sb.Append(      uniqueID + "_trackStatus = true;");
			sb.Append(      "subscriptionButtonOut();");
			sb.Append(    "}");
			sb.Append(  "} else {");
			sb.Append(    "subscriptionButtonOut();");
			sb.Append(    "alert(response.error);");
			sb.Append(  "}");
			sb.Append("}");
			sb.Append("</script>");

			Page.RegisterClientScriptBlock("ThreadSubscribeCallback", sb.ToString());
		}

		#endregion

		#region Event Handlers/Callbacks

		/// <summary>
		/// This method is the callback when a user clicks on the button to toggle their tracking status.  It calls the abstract Toggle()
		/// method to switch the user's tracking status and then returns whether or not it was successful.
		/// </summary>
		/// <returns>This returns true/false to indicate whether the switch was successful or not.</returns>
		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public bool ToggleEmailReplies(int threadID)
		{
			try
			{
				CSContext context = CSContext.Current;
				if(!context.User.IsAnonymous)
				{
					EmailSubscriptionType newSubType = EmailSubscriptionType.None;

					if (IsTracked)
					{
						newSubType = (EmailSubscriptionType)2 ;
					}

					ResLinkSection section = ResLinkSection.GetSection(CSContext.Current.SectionID);

					section.SetSectionSubscriptionType(newSubType);

					return true;
				}
				return false;
			}
			catch(Exception e)
			{
				new CSException(CSExceptionType.UnknownError, "Error in ThreadSubscribeLinkButton callback", e).Log();
				throw e;
			}
		}

		#endregion

	}
}
